package com.shan.oss.web.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.shan.common.util.PropertiesFileUtil;
import com.shan.oss.constant.OssConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author: shanzheng <br/>
 * Description: 阿里云存储对象service<br/>
 * Date： 16:07 2017/9/6.<br/>
 * Modified By: <br/>
 */
@Service
public class AliyunOssService {
    private static Logger logger = LoggerFactory.getLogger(AliyunOssService.class);

    @Autowired
    private OSSClient aliyunOssClient;

    /**
     * Description: 生成策略
     *
     * @author: shanzheng
     * @date: 16:07 2017/9/7
     * @return: com.alibaba.fastjson.JSONObject
     */
    public JSONObject policy() {
        JSONObject result = new JSONObject();
        //存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = sdf.format(new Date());
        // 签名有效期
        long expireEndTime = System.currentTimeMillis() + OssConstant.ALIYUN_OSS_EXPIRE * 1000;
        Date expiration = new Date(expireEndTime);

        //文件大小
        long maxSize = OssConstant.ALIYUN_OSS_MAX_SIZE * 1024 * 1024;//10G

        //回调
        JSONObject callback = new JSONObject();
        callback.put("callbackUrl", PropertiesFileUtil.getInstance("config").get("aliyun.oss.callback"));//todo 需要放到OssConstant中去
        callback.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        callback.put("callbackBodyType", "application/x-www-form-urlencoded");
        // 提交节点即阿里页面显示的外网域名
        String action = "http://" + OssConstant.ALIYUN_OSS_BUCKET_NAME + "." + OssConstant.ALIYUN_OSS_ENDPOINT;

        try {
            //策略条件
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);//添加大小
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);//添加存储文件的名字
            String postPolicy = aliyunOssClient.generatePostPolicy(expiration, policyConditions);//形成post策略
            byte[] binaryData = postPolicy.getBytes("utf-8");//策略编码格式
            String policy = BinaryUtil.toBase64String(binaryData);//转成base64格式
            String signature = aliyunOssClient.calculatePostSignature(postPolicy);//计算得到post 签名
            String callbackData = BinaryUtil.toBase64String(callback.toString().getBytes("utf-8"));//回调的地址变成utf-8编码格式
            // 返回结果
            result.put("OSSAccessKeyId", aliyunOssClient.getCredentialsProvider().getCredentials().getAccessKeyId());
            result.put("policy", policy);
            result.put("signature", signature);
            result.put("dir", dir);
            result.put("callback", callbackData);
            result.put("action", action);
        } catch (Exception e) {
            logger.error("签名生成失败", e);
        }
        return result;
    }

}
